<template>
  <div class="app-container">
    <!-- 简化的搜索表单 - 只保留常用搜索字段 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入手机号"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="userGender">
        <el-select v-model="queryParams.userGender" placeholder="请选择性别" clearable style="width: 120px">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户等级" prop="userLevel">
        <el-select v-model="queryParams.userLevel" placeholder="请选择等级" clearable style="width: 120px">
          <el-option label="普通用户" :value="0" />
          <el-option label="VIP用户" :value="1" />
          <el-option label="超级VIP" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
          <el-option label="开启" value="开启" />
          <el-option label="关闭" value="关闭" />
          <el-option label="删除" value="删除" />
        </el-select>
      </el-form-item>
      <el-form-item label="所在城市" prop="userCity">
        <el-input
          v-model="queryParams.userCity"
          placeholder="请输入城市"
          clearable
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:users:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:users:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 简化的数据表格 - 只显示关键字段 -->
    <el-table 
      v-loading="loading" 
      :data="usersList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="userid" width="80" />
      <el-table-column label="头像" align="center" prop="userAvatarUrl" width="80">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.userAvatarUrl"
            style="width: 50px; height: 50px; border-radius: 50%"
            :src="scope.row.userAvatarUrl" 
            :preview-src-list="[scope.row.userAvatarUrl]"
            fit="cover">
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username" min-width="120" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="userPhone" width="130" />
      <el-table-column label="性别" align="center" prop="userGender" width="70">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.userGender === '男'" type="primary" size="small">男</el-tag>
          <el-tag v-else-if="scope.row.userGender === '女'" type="danger" size="small">女</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="userAge" width="70" />
      <el-table-column label="城市" align="center" prop="userCity" min-width="120" show-overflow-tooltip />
      <el-table-column label="等级" align="center" prop="userLevel" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.userLevel === 0" type="info" size="small">普通</el-tag>
          <el-tag v-else-if="scope.row.userLevel === 1" type="warning" size="small">VIP</el-tag>
          <el-tag v-else-if="scope.row.userLevel === 2" type="danger" size="small">超级VIP</el-tag>
          <span v-else>{{ scope.row.userLevel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获赞" align="center" prop="userLikes" width="80" />
      <el-table-column label="粉丝" align="center" prop="userFollowers" width="80" />
      <el-table-column label="积分" align="center" prop="userPoints" width="90" />
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '开启'" type="success" size="small">开启</el-tag>
          <el-tag v-else-if="scope.row.status === '关闭'" type="warning" size="small">关闭</el-tag>
          <el-tag v-else-if="scope.row.status === '删除'" type="danger" size="small">删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录" align="center" prop="lastLogin" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastLogin, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:users:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:users:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 优化后的添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息标签页 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="用户头像" prop="userAvatarUrl">
                  <image-upload 
                    v-model="form.userAvatarUrl" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" placeholder="请输入用户名" maxlength="50" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="userPhone">
                  <el-input v-model="form.userPhone" placeholder="请输入手机号" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="userEmail">
                  <el-input v-model="form.userEmail" placeholder="请输入邮箱" type="email" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="userGender">
                  <el-radio-group v-model="form.userGender">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄" prop="userAge">
                  <el-input-number v-model="form.userAge" :min="1" :max="150" placeholder="请输入年龄" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生日" prop="userBirthday">
                  <el-date-picker 
                    clearable 
                    style="width: 100%"
                    v-model="form.userBirthday"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择生日">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在城市" prop="userCity">
                  <el-input v-model="form.userCity" placeholder="请输入所在城市" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="常去地点" prop="userFrequentPlaces">
                  <el-input v-model="form.userFrequentPlaces" placeholder="请输入常去地点" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="个性签名" prop="userSignature">
                  <el-input 
                    v-model="form.userSignature" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入个性签名" 
                    maxlength="200"
                    show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 账户信息标签页 -->
          <el-tab-pane label="账户信息" name="account">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户等级" prop="userLevel">
                  <el-select v-model="form.userLevel" placeholder="请选择用户等级" style="width: 100%">
                    <el-option label="普通用户" :value="0" />
                    <el-option label="VIP用户" :value="1" />
                    <el-option label="超级VIP" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="账户状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio label="开启">开启</el-radio>
                    <el-radio label="关闭">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="获赞数量" prop="userLikes">
                  <el-input-number v-model="form.userLikes" :min="0" placeholder="获赞数" style="width: 100%" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="粉丝数量" prop="userFollowers">
                  <el-input-number v-model="form.userFollowers" :min="0" placeholder="粉丝数" style="width: 100%" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户积分" prop="userPoints">
                  <el-input-number v-model="form.userPoints" :min="0" placeholder="积分" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 扩展信息标签页 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="用户标签" prop="userTags">
                  <el-tag
                    v-for="tag in userTagsList"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleTagClose(tag)"
                    style="margin-right: 10px;">
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputTagVisible"
                    v-model="inputTagValue"
                    ref="saveTagInput"
                    size="small"
                    style="width: 120px;"
                    @keyup.enter.native="handleInputTagConfirm"
                    @blur="handleInputTagConfirm">
                  </el-input>
                  <el-button v-else size="small" @click="showTagInput">+ 新标签</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="兴趣爱好" prop="userHobbies">
                  <el-checkbox-group v-model="userHobbiesList">
                    <el-checkbox label="运动">运动</el-checkbox>
                    <el-checkbox label="音乐">音乐</el-checkbox>
                    <el-checkbox label="阅读">阅读</el-checkbox>
                    <el-checkbox label="旅游">旅游</el-checkbox>
                    <el-checkbox label="摄影">摄影</el-checkbox>
                    <el-checkbox label="美食">美食</el-checkbox>
                    <el-checkbox label="游戏">游戏</el-checkbox>
                    <el-checkbox label="电影">电影</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="相册图片" prop="userImgUrls">
                  <image-upload 
                    v-model="form.userImgUrls" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsers, getUsers, delUsers, addUsers, updateUsers } from "@/api/system/users";

export default {
  name: "Users",
  components: {
    ImageUpload: () => import("@/components/ImageUpload")
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      usersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: 'basic',
      // 标签输入
      inputTagVisible: false,
      inputTagValue: '',
      userTagsList: [],
      // 兴趣爱好列表
      userHobbiesList: [],
      // 查询参数（简化后）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userPhone: null,
        username: null,
        userGender: null,
        userLevel: null,
        status: null,
        userCity: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 2, max: 50, message: "用户名长度在 2 到 50 个字符", trigger: "blur" }
        ],
        userPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        userEmail: [
          { type: 'email', message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
        userAge: [
          { type: 'number', min: 1, max: 150, message: "年龄必须在1-150之间", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listUsers(this.queryParams).then(response => {
        this.usersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userid: null,
        userPhone: null,
        userEmail: null,
        username: null,
        userAvatarUrl: null,
        userAge: null,
        userGender: null,
        userSignature: null,
        userTags: null,
        userLikes: 0,
        userFollowers: 0,
        userPoints: 0,
        userHobbies: null,
        userCity: null,
        userImgUrls: null,
        userFrequentPlaces: null,
        userBirthday: null,
        userLevel: 0,
        status: '开启'
      };
      this.userTagsList = [];
      this.userHobbiesList = [];
      this.activeTab = 'basic';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userid = row.userid || this.ids
      getUsers(userid).then(response => {
        this.form = response.data;
        
        // 处理JSON字段
        if (this.form.userTags) {
          this.userTagsList = typeof this.form.userTags === 'string' 
            ? JSON.parse(this.form.userTags) 
            : this.form.userTags;
        }
        if (this.form.userHobbies) {
          this.userHobbiesList = typeof this.form.userHobbies === 'string' 
            ? JSON.parse(this.form.userHobbies) 
            : this.form.userHobbies;
        }
        // 将 userImgUrls 从 JSON 数组转换为逗号分隔字符串（ImageUpload 组件需要）
        if (this.form.userImgUrls) {
          const urls = typeof this.form.userImgUrls === 'string' 
            ? JSON.parse(this.form.userImgUrls) 
            : this.form.userImgUrls;
          this.form.userImgUrls = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理JSON字段
          const submitForm = { ...this.form };
          submitForm.userTags = this.userTagsList.length > 0 ? JSON.stringify(this.userTagsList) : null;
          submitForm.userHobbies = this.userHobbiesList.length > 0 ? JSON.stringify(this.userHobbiesList) : null;
          
          // 将 userImgUrls 从逗号分隔字符串转换为 JSON 数组格式（数据库需要）
          if (submitForm.userImgUrls && typeof submitForm.userImgUrls === 'string') {
            const urlArray = submitForm.userImgUrls.split(',').filter(url => url.trim());
            submitForm.userImgUrls = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          if (submitForm.userid != null) {
            updateUsers(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsers(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userids = row.userid || this.ids;
      this.$modal.confirm('是否确认删除用户信息编号为"' + userids + '"的数据项？').then(function() {
        return delUsers(userids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/users/export', {
        ...this.queryParams
      }, `users_${new Date().getTime()}.xlsx`)
    },
    /** 标签相关方法 */
    handleTagClose(tag) {
      this.userTagsList.splice(this.userTagsList.indexOf(tag), 1);
    },
    showTagInput() {
      this.inputTagVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputTagConfirm() {
      let inputTagValue = this.inputTagValue;
      if (inputTagValue && !this.userTagsList.includes(inputTagValue)) {
        this.userTagsList.push(inputTagValue);
      }
      this.inputTagVisible = false;
      this.inputTagValue = '';
    }
  }
};
</script>

<style scoped>
/* 页面样式由 ImageUpload 组件自动处理 */
</style>
